import { store } from "@/store"
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getAuth, setAuth, clear }  from "@/utils/storage"
import { flushLoginApi, loginApi } from '@/api/admin/login'


export const useAuthStore = defineStore("Auth", () => {
   
    const adminInfo = ref()
    const authorize = ref()

    /**
     * 
     * @returns 
     */
    function getAccessToken(){
        if(authorize.value) return authorize.value
        let accessToken  = getAuth()
        if(accessToken){
            authorize.value = accessToken
        }
        return accessToken
    }

    /**
     * 
     * @param email 
     * @param code 
     * @returns 
     */
    function login(data: any){
        return new Promise((resolve, reject) => {
            loginApi(data).then(res => {
                const token = res.data.authorization
                authorize.value = token
                setAuth(token)
                const userInfo = res.data.userInfo
                adminInfo.value = userInfo
                resolve(userInfo)
            }).catch(err => {
                 reject(err)
            })
        })
    }

    /**
     * 
     */
    function flushLogin(){
        return new Promise((resolve, reject) => {
           const token = getAccessToken()
           if(token){
               flushLoginApi().then(res => {
                const token = res.data.authorization
                authorize.value = token
                setAuth(token)
                const userInfo = res.data.userInfo
                adminInfo.value = userInfo
                resolve(userInfo)
            }).catch(err => {
                reject(err)
            })
           }else{
                clear()
                adminInfo.value = undefined
                resolve(undefined) 
           }
        })
    }


    return {
        getAccessToken,
        
        flushLogin, login
    }

})

export function useAuthStoreHook() {
    return useAuthStore(store);
}